/**
 * Created by Administrator on 2018/11/23 0023.
 */

var request = require("request");
var qs = require("qs");
const CONF = require("./config/conf");

module.exports = function (app) {

//请求地址格式化
    app.use(function (req,res,next) {
        //解析来源地址，如果是线上的，应该将端口去掉
        req._fromUrl =  req.protocol + "://" + req.hostname + CONF.port + req.originalUrl;
        res.locals._fromUrl = encodeURIComponent( req._fromUrl);
        next();
    });


//拦截所有带token的，访问
    app.use(function (req,res,next) {
        var _token = req.query._token || '';
        res.locals._userinfo = '';
        res.locals._conf = CONF;
        console.log("sessid:" + req.sessionID)
        if(req.session.userinfo){
            console.log("使用自己的session",req.session.userinfo);
            res.locals._userinfo = req.session.userinfo;
            next();
            return ;
        };
        if(_token){
            //去sso，换取用户信息
            request({
                timeout:5000,    // 设置超时
                method:'POST',    //请求方式
                url:CONF.tokenCheck, //url
                form:{
                    _token:_token,
                    _app:CONF.appName,
                    _sessionid:req.sessionID
                }
            },function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    try{
                        body = JSON.parse(body);
                    }catch(e){

                    }
                    if(body.code == 1){
                        req.session.userinfo = body.data;
                        res.locals._userinfo = body.data;

                    }
                    console.log(body);
                }
                next();
            });
        }else if(!req.session.isCheck){
            req.session.isCheck = true;
            var url = CONF.ssoLoginNormal;
            var cd = res.locals._fromUrl;
            url = url + cd;
            res.redirect(url)
        }else {
            next();
        }
    });

//去除地址上面的token
//将域名上面的 _token 参数去掉,避免复制到其它地方
    app.use(function (req,res,next) {
        var arr = req.originalUrl.split("?");
        var obj = qs.parse(arr[1]);
        if(obj["_token"]){
            delete obj._token;
            var search = qs.stringify(obj);
            var  url = arr[0];
            if(search){
                url = url + "?" + search;
            }
            res.redirect(url);
        }else{
            next();
        }
    })

}